﻿using Hangfire;
using Hangfire.MySql;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Core.AdminUI.V2.Utils
{
    /// <summary>
    /// Hangfire 定时调度
    /// </summary>
    public static class InitHangfire
    {
        /// <summary>
        /// Hangfire 注册
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddInitHangfire(this IServiceCollection services)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            #region Hangfire配置

            GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(services.BuildServiceProvider()));

            var storage = new MySqlStorage(AdminConfig.DbConnections.HangfireConnectionString
                  , new MySqlStorageOptions
                  {
                      PrepareSchemaIfNecessary = true,
                      QueuePollInterval = TimeSpan.FromSeconds(1)
                  });

            //指定数据库
            services.AddHangfire(p => p.UseStorage(storage));
            services.AddHangfireServer();

            //给服务生成几个队列
            //services.AddHangfireServer(opt =>
            //{
            //    opt.ServerName = "TreeHole-Dev 调度任务";
            //    opt.WorkerCount = 4;
            //    opt.Queues = new[] { "Quesues1", "Quesues2", "Quesues3" };
            //});
            #endregion


        }
    }
    public class ContainerJobActivator : JobActivator
    {
        private readonly IServiceProvider _serviceProvider;

        public ContainerJobActivator(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public override object ActivateJob(Type type)
        {
            return _serviceProvider.GetService(type);
        }
    }

}
